package com.zx.flow.core.execute.eventhandler;

import com.zx.flow.api.dict.FlowDict.Event;
import com.zx.flow.api.dict.FlowDict.OperatorRule;
import com.zx.flow.api.execute.model.FlowContext;
import com.zx.flow.api.execute.model.FlowNode;
import com.zx.flow.api.execute.model.FlowOperator;
import com.zx.flow.api.execute.request.FlowParamCommunicate;
import com.zx.flow.api.execute.request.FlowParamNodeEntry;
import com.zx.flow.api.execute.request.FlowParamNodeFinish;
import com.zx.flow.api.execute.response.FlowResult;
import com.zx.flow.api.util.AssertUtil;
import com.zx.flow.core.execute.EventHandler;
import org.springframework.util.CollectionUtils;

/**
 * 事件处理器【流程->沟通】
 */
public class EventFlowCommunicateHandler extends EventHandler<FlowParamCommunicate> {

    @Override
    public boolean in(FlowContext flow, FlowParamCommunicate param) {
        AssertUtil.checkOperator(flow, param.getNodeId(), param.getAccountCode());
        return flow != null && !CollectionUtils.isEmpty(param.getOperators());
    }

    @Override
    public FlowResult on(FlowContext flow, FlowParamCommunicate param) {
        // 获得当前节点
        FlowNode currentNode = AssertUtil.checkCurrentNodeId(flow, param.getNodeId());
        // 结束当前节点
        flow = this.execute(new FlowParamNodeFinish(param.getId(), param.getNodeId(), currentNode.getNodeCurrentCode(),
                Event.nodeCommunicate, param.getRemark(), param.getAccountCode())).getFlowContext();
        // 设置操作人权限
        for (FlowOperator operator : param.getOperators()) {
            operator.setRule(OperatorRule.communicate.getCode());
        }
        // 指定操作人
        flow = this.execute(
                        new FlowParamNodeEntry(flow.getId(), currentNode.getNodeCurrentCode(), param.getOperators()))
                .getFlowContext();
        // 触发监听
        this.listener(currentNode, Event.nodeCommunicate);
        return FlowResult.ok(flow);
    }
}
